// src/components/WebSocketStatus.jsx
import { useState, useEffect } from 'react'
import { Badge, Tooltip } from '@/utils/antd-imports'
import { WifiOutlined, CloseOutlined } from '@/utils/icons'
import wsManager from '../utils/websocket'

const WebSocketStatus = () => {
  const [status, setStatus] = useState({
    isConnected: false,
    reconnectAttempts: 0,
    url: ''
  })

  useEffect(() => {
    // 获取初始状态
    setStatus(wsManager.getConnectionStatus())

    // 监听连接状态变化
    const handleConnected = () => {
      setStatus(wsManager.getConnectionStatus())
    }

    const handleDisconnected = () => {
      setStatus(wsManager.getConnectionStatus())
    }

    const handleError = () => {
      setStatus(wsManager.getConnectionStatus())
    }

    // 添加监听器
    wsManager.addListener('connected', handleConnected)
    wsManager.addListener('disconnected', handleDisconnected)
    wsManager.addListener('error', handleError)

    // 定期更新状态
    const interval = setInterval(() => {
      setStatus(wsManager.getConnectionStatus())
    }, 5000)

    return () => {
      wsManager.removeListener('connected', handleConnected)
      wsManager.removeListener('disconnected', handleDisconnected)
      wsManager.removeListener('error', handleError)
      clearInterval(interval)
    }
  }, [])

  const getStatusColor = () => {
    if (status.isConnected) return 'green'
    if (status.reconnectAttempts > 0) return 'orange'
    return 'red'
  }

  const getStatusText = () => {
    if (status.isConnected) return '已连接'
    if (status.reconnectAttempts > 0) return `重连中 (${status.reconnectAttempts})`
    return '未连接'
  }

  const getTooltipText = () => {
    if (status.isConnected) {
      return `WebSocket已连接到: ${status.url}`
    }
    if (status.reconnectAttempts > 0) {
      return `正在尝试重连到: ${status.url}`
    }
    return `WebSocket未连接到: ${status.url}`
  }

  return (
    <Tooltip title={getTooltipText()}>
      <Badge 
        color={getStatusColor()} 
        text={getStatusText()}
        style={{ fontSize: '12px' }}
      >
        {status.isConnected ? <WifiOutlined /> : <CloseOutlined />}
      </Badge>
    </Tooltip>
  )
}

export default WebSocketStatus
